import getpath
import os
import logging
import csv
import myglobal
import config_json
from delegates import EditDelegateQt,DateTimeEditDelegateQt,DoubleViewDelegate,FloatEditDelegateQt
import sample
from PyQt5 import QtWidgets
from DlgYanghua import DlgYanghua
import re
import openpyxl
import weight
import re
class SampleGuangdu(sample.Sample):
    def __init__(self):
        super().__init__()
        self.V1=None
        self.V2=None
        self.A=None
        self.c=None
        self.item=None
        pass
class MyDb(weight.MyDb):
    def addOne(self):
        n=SampleGuangdu()
        n.sampleid="001"
        return n
    def __init__(self,mainw):
        super().__init__(mainw)
        self.properties = [
            {"ele":None,"delegate":self.editDelegate,'width':130,'attr': "sampleid",'visible':True,  'header': "中心编号"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "mass",'visible':True,  'header': "试料质量"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "V",'visible':True,  'header': "稀释后总体积"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "V2",'visible':True,  'header': "分取体积"},
            {"ele":None,"delegate":self.floatEdit,'width':100,'attr': "A",'visible':True,  'header': "吸光度A"},
            {"ele":None,"delegate":self.floatEdit,'width':100,'attr': "c",'visible':True,  'header': "对应浓度"},
            {"xishu":None,"ele":config_json.setting["weight"]["ele"],"delegate":self.editDelegate,'width':80,'attr': "item",'visible':True,  'header': config_json.setting["weight"]["ele"]},
            {"ele":None,"delegate":self.editDelegate,'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
    def calc(self):
        for one in self.mainw.appends:
            k=one[0]
            w=one[1]
            l=w.l.text()
            v=w.t.text()
            config_json.setting["append"]["guangdu"][k]=[l,v]
        n=len(self.mainw.objects2)
        A0=0
        for i in range(n):
            o=self.mainw.objects2[i]
            if "A0" in o.sampleid:
                A0=myglobal.myfloat(o.A)
                break
        b=myglobal.myfloat(self.mainw.appends[2][1].t.text())#arg2
        a=myglobal.myfloat(self.mainw.appends[3][1].t.text())#arg3
        V1=myglobal.myfloat(self.mainw.appends[4][1].t.text())#arg3
        for i in range(n):
            try:
                o=self.mainw.objects2[i]
                A=myglobal.myfloat(o.A)
                m=myglobal.myfloat(o.mass)
                V=myglobal.myfloat(o.V)
                V2=myglobal.myfloat(o.V2)
                c=(A-A0-a)/b
                o.c=c
                o.item=(c*V1)/(m*1000000)*V/V2*100
            except ZeroDivisionError:
                pass
        self.mainw.refresh_grid2()
    def import_text_bytitle(self, txt):
        logging.info(txt)
        data = []
        for row in txt.split("\n"):
            # logging.info(row)
            data.append(row.split("\t"))
        title = data[0]
        data = data[1:]
        logging.info(title)
        for f in self.properties:
            f["at"] = myglobal.in_list(f["header"],title )
        if len(self.mainw.objects)>0:
            num=self.mainw.objects[-1].num+1
        else:
            num=0
        r=[]
        for one in data:
            # logging.info("=====================")
            # logging.info(one)
            if len(one) < 2:
                continue
            fs = []
            vs = []
            for f in self.properties:
                if f["at"] != -1:
                    fs.append( f["attr"])
                    vs.append(one[f["at"]] )
            print(fs,vs)
            s=SampleGuangdu()
            for i in range(len(fs)):
                setattr(s,fs[i],vs[i])
            s.num=num
            r.append(s)
        print(r)
        return r         
    def output_xlsx(self, filepath):
        n =len(self.mainw.objects2)
        if n == 0:
            return
        filepath = filepath + ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        wb = openpyxl.Workbook()
        # 3. 构建列表头
        row = ["id", "mass","V1","V2","A","c","备注"]
        for f in self.properties:#item
            if f["visible"] and f["ele"]!=None:
                row.append(f["header"])
        ws = wb.active
        ws.append(row)
        for row_idx in range(n):
            record = self.mainw.objects2[row_idx]
            row = [record.sampleid,record.mass,record.V1,record.V2,record.A,record.c,record.beizhu]
            for f in self.properties:#item
                if f["visible"] and f["ele"]!=None:
                    v=getattr(record,f["attr"])
                    xishu=f.get("xishu")
                    if xishu:
                        v=myglobal.myfloat(v)*xishu
                    row.append(v)
            ws.append(row)
        ffbh = self.mainw.ui.cmb_ffbh.text()
        syy = self.mainw.ui.cmb_syy.text()
        ysry = self.mainw.ui.cmb_ysry.text()
        syyqm = self.mainw.ui.cmb_syyqm.text()
        row = ["ffbh&" + ffbh, "", "", "", ""]
        ws.append(row)
        row = ["syy&" + syy, "", "", "", ""]
        ws.append(row)
        row = ["ysry&" + ysry, "", "", "", ""]
        ws.append(row)
        row = ["syyqm&" + syyqm, "", "", "", ""]
        ws.append(row)
        ff2= self.mainw.ui.cmb_ff2.text()
        js2= self.mainw.ui.cmb_js2.text()
        ws.append(["ejff&" + ff2,"", "", "", ""])  # todo
        ws.append(["ejfxjs&" + js2, "", "", "", ""])
        yqbh=self.mainw.ui.lineEdit_yqbh.text()
        row = ["yqbh&" + yqbh, "", "", "", ""]
        ws.append(row)
        for one in self.mainw.appends:
            k=one[0]
            w=one[1]
            l=w.l.text()
            v=w.t.text()
            row = [k+"&" + v,l, "", "", ""]
            ws.append(row)
            config_json.setting["append"]["guangdu"][k]=[l,v]
        ws.column_dimensions['A'].width = 30.0
        wb.save(filepath)
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum())                      
        self.mainw.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
if __name__=="__main__":
    file = os.path.join(getpath.getpath(), "930.csv")
    config_json.read_setting()
    config_json.setting['database'] = file
    db = MyDb(None)
    objs=db.getDataDays(200)
    for obj in objs:
        print(obj.sampleid)
        for one in obj.items.keys():
            print(one[0]+"_"+one[1],getattr(obj,one[0]+"_"+one[1]))       